import { useState } from 'react';
import { message } from 'antd';
import { api, ApiError } from '../utils/api';
import { API_ENDPOINTS } from '../constants/api';

export interface Session {
  id: string;
  roomId: string;
  startTime: string;
  endTime: string | null;
  createdAt: string;
  displayTitle: string;
  title?: string;
  room?: {
    id: string;
    title: string;
    streamerName: string;
  };
}

export interface SessionsResponse {
  sessions: Session[];
}

export interface SessionGiftBreakdownItem {
  giftId: string | null;
  name: string;
  quantity: number;
  price: number;
  amount: number;
  icon?: string | null;
  type?: number | null;
}

export interface SessionGiftSummary {
  totalRecords: number;
  totalQuantity: number;
  totalGiftTypes: number;
  totalSoundWave: number;
  uniqueUsers: number;
  breakdown: SessionGiftBreakdownItem[];
}

export const useSessions = () => {
  const [sessions, setSessions] = useState<Session[]>([]);
  const [loading, setLoading] = useState(false);

  // 获取session列表：如果提供roomId，则按房间查询，否则获取全部
  const fetchSessions = async (roomId?: string) => {
    setLoading(true);
    try {
      const url = roomId ? API_ENDPOINTS.SESSIONS_BY_ROOM(roomId) : API_ENDPOINTS.SESSIONS;
      const data = await api.get<SessionsResponse>(url);
      const sessionsData = data.data?.sessions || [];
      const sorted = [...sessionsData].sort((a, b) => {
        const aTime = a.endTime ? new Date(a.endTime).getTime() : new Date(a.startTime).getTime();
        const bTime = b.endTime ? new Date(b.endTime).getTime() : new Date(b.startTime).getTime();
        return bTime - aTime; // 倒序，最新在前
      });
      setSessions(sorted);
    } catch (error) {
      if (error instanceof ApiError) {
        message.error(`获取直播场次失败: ${error.message}`);
      } else {
        message.error('网络错误，请稍后重试');
      }
      setSessions([]);
    } finally {
      setLoading(false);
    }
  };

  // 获取指定session详情
  const fetchSessionDetails = async (sessionId: string) => {
    try {
      const data = await api.get<any>(API_ENDPOINTS.SESSION_DETAILS(sessionId));
      return data.data;
    } catch (error) {
      if (error instanceof ApiError) {
        message.error(`获取会话详情失败: ${error.message}`);
      } else {
        message.error('网络错误，请稍后重试');
      }
      throw error;
    }
  };

  const fetchSessionGiftStats = async (sessionId: string) => {
    try {
      const response = await api.get<SessionGiftSummary>(API_ENDPOINTS.SESSION_GIFT_STATS(sessionId));
      return response.data;
    } catch (error) {
      if (error instanceof ApiError) {
        message.error(`获取礼物统计失败: ${error.message}`);
      } else {
        message.error('网络错误，请稍后重试');
      }
      throw error;
    }
  };

  const deleteSession = async (sessionId: string) => {
    try {
      await api.delete(API_ENDPOINTS.SESSION_DELETE(sessionId));
      message.success('会话已删除');
      setSessions(prev => prev.filter(session => session.id !== sessionId));
      return true;
    } catch (error) {
      if (error instanceof ApiError) {
        message.error(`删除会话失败: ${error.message}`);
      } else {
        message.error('删除会话失败');
      }
      return false;
    }
  };

  return {
    sessions,
    loading,
    fetchSessions,
    fetchSessionDetails,
    fetchSessionGiftStats,
    deleteSession,
  };
};
